package com.scrcu.cloud.wechat.home.endpoint.common.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements Ilock{

    private String name;
    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "Redislock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    private static final DefaultRedisScript<Long> UNLOCKSCRIPT;
    static{
        UNLOCKSCRIPT = new DefaultRedisScript<>();
        UNLOCKSCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCKSCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //获取锁
//        long threadId = Thread.currentThread().getId();
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);  //防止拆箱的时候空指针异常
    }

//    @Override
//    public void unlock() {
//        //释放锁
//        String threadId = ID_PREFIX + Thread.currentThread().getId();
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//
//        //必须保证判断和删除是原子操作，不然也有可能出现误删，详情见黑马redis 61 62集
//        if (threadId.equals(id)){ //相同才释放,不同就不释放了
//            //再判断的过程中如果发生gc回收 造成阻塞，可能也导致这里锁不一致，因此需要保证原子性
//            stringRedisTemplate.delete(KEY_PREFIX + name);
//        }
//    }

    public void unlock() {
        //调用lua,满足原子性
        stringRedisTemplate.execute(UNLOCKSCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId());
    }

}
